//
//  ObjectDetailView.m
//  JinMaJiaDemo
//
//  Created by GripMeMory on 16/1/25.
//  Copyright © 2016年 GripMeMory. All rights reserved.
//

#import "ObjectDetailView.h"

#define kImageViewHeight 500 / 2
#define kBiddingNoticeLabelHeight 50 / 2
#define kBiddingNoticeLabelWidth 380 / 2
#define kBiddingNoticeLabelBottomMargin 10

#define kTitleLabelHeight 150 / 2
#define kTitleLabelLeftMargin 15
#define kStarringLabelWidth 70
#define kPriceLabelLeftMargin 90 / 2

#define kBottomLabelHeight 90 / 2

#define kBiddingImageViewWidth 60

#define kFontSize 11

@implementation ObjectDetailView

{
    UIImageView *_titleImageView;
    UILabel *_bidingNoticeLabe;
    UILabel *_titleLabel;
    UILabel *_starringLabel;
    UILabel *_priceLabel;
    UIImageView *_biddingImageView;
    UILabel *_countDownLabel;
    UILabel *_startingPriceLabel;
    UILabel *_raiseLevelLabel;
    UILabel *_currentStateLabel;
    
    UIView *_separateLine1;
    UIView *_separateLine2;
}

- (id)init{
    self = [super init];
    if (self) {
        _titleImageView = [[UIImageView alloc] init];
        _bidingNoticeLabe = [[UILabel alloc] init];
        _titleLabel = [[UILabel alloc] init];
        _starringLabel = [[UILabel alloc] init];
        _priceLabel = [[UILabel alloc] init];
        _biddingImageView = [[UIImageView alloc] init];
        _countDownLabel = [[UILabel alloc] init];
        _startingPriceLabel = [[UILabel alloc] init];
        _raiseLevelLabel = [[UILabel alloc] init];
        _currentStateLabel = [[UILabel alloc] init];
        
        [self addSubview:_titleImageView];
        [self addSubview:_bidingNoticeLabe];
        [self addSubview:_titleLabel];
        [self addSubview:_starringLabel];
        [self addSubview:_priceLabel];
        [self addSubview:_bidingNoticeLabe];
        [self addSubview:_countDownLabel];
        [self addSubview:_startingPriceLabel];
        [self addSubview:_raiseLevelLabel];
        [self addSubview:_currentStateLabel];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
        _titleImageView = [[UIImageView alloc] init];
        _bidingNoticeLabe = [[UILabel alloc] init];
        _titleLabel = [[UILabel alloc] init];
        _starringLabel = [[UILabel alloc] init];
        _priceLabel = [[UILabel alloc] init];
        _biddingImageView = [[UIImageView alloc] init];
        _countDownLabel = [[UILabel alloc] init];
        _startingPriceLabel = [[UILabel alloc] init];
        _raiseLevelLabel = [[UILabel alloc] init];
        _currentStateLabel = [[UILabel alloc] init];
        
        _separateLine1 = [[UIView alloc] init];
        _separateLine2 = [[UIView alloc] init];
        _separateLine1.backgroundColor = RGB_COLOR(@"#d5a540");
        _separateLine2.backgroundColor = RGB_COLOR(@"#d5a540");
        [self addSubview:_separateLine1];
        [self addSubview:_separateLine2];
        
        [self addSubview:_titleImageView];
        [self addSubview:_bidingNoticeLabe];
        [self addSubview:_titleLabel];
        [self addSubview:_starringLabel];
        [self addSubview:_priceLabel];
        [self addSubview:_bidingNoticeLabe];
        [self addSubview:_countDownLabel];
        [self addSubview:_startingPriceLabel];
        [self addSubview:_raiseLevelLabel];
        [self addSubview:_currentStateLabel];
        
    }
    return self;
}

- (void)layoutSubviews{
    
    _titleImageView.frame = CGRectMake(0, 0, UISCREENWIDTH, kImageViewHeight);
    
    _bidingNoticeLabe.frame = CGRectMake(0, _titleImageView.bottom - kBiddingNoticeLabelBottomMargin - kBiddingNoticeLabelHeight, kBiddingNoticeLabelWidth, kBiddingNoticeLabelHeight);
    _bidingNoticeLabe.centerX = _titleImageView.centerX;
    _bidingNoticeLabe.backgroundColor = RGB_COLOR(@"#d5a540");
    _bidingNoticeLabe.text = @"您当前为最高报价所属人";
    _bidingNoticeLabe.textColor = [UIColor whiteColor];
    _bidingNoticeLabe.font = [UIFont systemFontOfSize:kFontSize];
    _bidingNoticeLabe.textAlignment = NSTextAlignmentCenter;
    
    _titleLabel.frame = CGRectMake(kTitleLabelLeftMargin, _titleImageView.bottom, UISCREENWIDTH - 2 * kTitleLabelLeftMargin, kTitleLabelHeight);
    _titleLabel.numberOfLines = 2;
    _titleLabel.font = [UIFont boldSystemFontOfSize:kFontSize + 2];
    
    _starringLabel.frame = CGRectMake(_titleLabel.right - kStarringLabelWidth, _titleLabel.top +  _titleLabel.height / 2, kStarringLabelWidth, _titleLabel.height / 2);
    _starringLabel.textColor = RGB_COLOR(@"#c9c9c9");
    _starringLabel.font = [UIFont systemFontOfSize:kFontSize];
    
    _separateLine1.frame = CGRectMake(_titleLabel.left, _titleLabel.bottom, _titleLabel.width, 1);
    
    _priceLabel.frame = CGRectMake(kTitleLabelLeftMargin + kPriceLabelLeftMargin, _separateLine1.bottom, _separateLine1.width - kBiddingImageViewWidth, kTitleLabelHeight / 2);
    _priceLabel.textAlignment = NSTextAlignmentLeft;

    _countDownLabel.frame = CGRectMake(_priceLabel.left, _priceLabel.bottom, _separateLine1.width - kBiddingImageViewWidth, kTitleLabelHeight / 2);
    _countDownLabel.textAlignment = NSTextAlignmentLeft;
    _countDownLabel.font = [UIFont systemFontOfSize:kFontSize];
    
    _separateLine2.frame = CGRectMake(_separateLine1.left, _countDownLabel.bottom, _separateLine1.width, 1);
    
    _startingPriceLabel.frame = CGRectMake(_separateLine2.left, _separateLine2.bottom, (UISCREENWIDTH - 2 * kTitleLabelLeftMargin) / 3, kBottomLabelHeight);
    _startingPriceLabel.numberOfLines = 2;
    _startingPriceLabel.textAlignment = NSTextAlignmentCenter;
    _startingPriceLabel.font = [UIFont systemFontOfSize:kFontSize];
    
    _raiseLevelLabel.frame = CGRectMake(_startingPriceLabel.right, _separateLine2.bottom, _startingPriceLabel.width, kBottomLabelHeight);
    _raiseLevelLabel.centerX = self.centerX;
    _raiseLevelLabel.numberOfLines = 2;
    _raiseLevelLabel.textAlignment = NSTextAlignmentCenter;
    _raiseLevelLabel.font = [UIFont systemFontOfSize:kFontSize];
    
    _currentStateLabel.frame = CGRectMake(self.right - kTitleLabelLeftMargin - _startingPriceLabel.width, _separateLine2.bottom, _startingPriceLabel.width, kBottomLabelHeight);
    _currentStateLabel.numberOfLines = 2;
    _currentStateLabel.textAlignment = NSTextAlignmentCenter;
    _currentStateLabel.font = [UIFont systemFontOfSize:kFontSize];
}

- (void)configureViewWithModel:(ObjectDetailModel *)model{
    _titleImageView.image = model.objectImage;
    _titleLabel.text = model.objectTitle;
    _starringLabel.text = [NSString stringWithFormat:@"%@次围观", model.starringCount];
    _priceLabel.attributedText = [self boldThePrice:model.currentPrice];
    [self getDifferenceWithBoundTime:model.boundTime];
    _startingPriceLabel.text = [NSString stringWithFormat:@"起始价：\n%@", model.startingPrice];
    _raiseLevelLabel.text = [NSString stringWithFormat:@"加价幅度：\n%@", model.raiseLevel];
    _currentStateLabel.text = [NSString stringWithFormat:@"所在期：\n%@", model.currentState];
}

- (NSAttributedString *)boldThePrice:(NSString *)price{
    
    NSString *string = [NSString stringWithFormat:@"当前最高报价： %@   元人民币", price];
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kFontSize]}];
    if (price != nil) {
        NSRange range = [string rangeOfString:price];
        [attributeString addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont italicSystemFontOfSize:kFontSize + 4]} range:range];
    }
    return attributeString;
    
}

- (void)getDifferenceWithBoundTime:(NSString *)boundtime{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = timeFormatter;
    
    NSDate *endTime = [formatter dateFromString:boundtime];
    NSDate *nowTime = [NSDate dateWithTimeIntervalSinceNow:0];
    
    NSTimeInterval end = [endTime timeIntervalSince1970];
    NSTimeInterval now = [nowTime timeIntervalSince1970];
    NSTimeInterval diff = end - now;
    
    __block int timeout = (int)diff;
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0)
        {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //倒计时结束
                //TODO: 修改modal followState 状态，刷新tableview，通知服务器或重新从服务器拉取数据
                _countDownLabel.text = @"time up";
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //更新界面
            
                NSString *lastString = [self updateTime:timeout];
                [_countDownLabel setAttributedText:[self configureDurationLabelTextAttributeWithString:lastString]];
                
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
    
}

- (NSString *)updateTime:(int)difference{
    
    NSString *day = @"";
    day = [NSString stringWithFormat:@"%02d", difference / 86400];
    
    difference = difference % 86400;
    
    NSString *time = [NSString stringWithFormat:@"%02d", difference / 3600];
    time = [NSString stringWithFormat:@"%@%02d", time, difference / 60 % 60];
    time = [NSString stringWithFormat:@"%@%02d",time, difference % 60 % 60];
    
    
    return [NSString stringWithFormat:@"%@%@", day, time];
}

- (NSAttributedString *)configureDurationLabelTextAttributeWithString:(NSString *)string{
    
    NSString *foreString2 = @"剩  余  时  间： ";
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    UIFont *font = [UIFont systemFontOfSize:kFontSize];
    UIColor *color = [UIColor blackColor];
    NSDictionary *dic = @{NSForegroundColorAttributeName:color, NSFontAttributeName:font};
    
    [attributedString addAttributes:dic range:NSMakeRange(0, string.length)];
    
    [attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@", foreString2]] atIndex:0];
    [attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:@"天"] atIndex:attributedString.length - 6];
    [attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:@"时"] atIndex:attributedString.length - 4];
    [attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:@"分"] atIndex:attributedString.length - 2];
    [attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:@"秒"] atIndex:attributedString.length];
    
    return attributedString;
}

@end
